﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThoughtWorks.QRCode.Codec;

namespace DSAManager.Utils
{
    public class QRCode
    {
        public Bitmap GetQRCodeImg(string writeStr, int size)
        {
            QRCodeEncoder qRCodeEncoder = new QRCodeEncoder();
            qRCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//设置二维码编码格式 
            qRCodeEncoder.QRCodeScale = size;//设置编码测量度             
            qRCodeEncoder.QRCodeVersion = 7;//设置编码版本   
            qRCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;//设置错误校验 
            Bitmap image = qRCodeEncoder.Encode(writeStr);
            return image;
        }

        private Bitmap GetLogoImg(int width, int height)
        {
            Bitmap newBmp = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + @"\logo.png");//获取图片对象             
            Bitmap bmp = new Bitmap(newBmp, width, height);//缩放             
            return bmp;
        }

        public string SaveQRCodeImg(string qrText, int size)
        {
            string qrname = Guid.NewGuid().ToString().Replace("-", "") + ".jpg";
            string qrdir = AppDomain.CurrentDomain.BaseDirectory + @"\qrcode\";
            string qrpath = qrdir + qrname;
            try
            {
                Bitmap bCode = GetQRCodeImg(qrText, size); //获取二维码图片
                int Y = bCode.Height;
                int X = bCode.Width;
                int width = IntExtension.Parse((X / 4).ToString());
                int height = IntExtension.Parse((Y / 4).ToString());

                Bitmap bLogo = GetLogoImg(width, height);//获取logo图片对象                     

                Point point = new Point(X / 2 - width / 2, Y / 2 - height / 2);//logo图片绘制到二维码上，这里将简单计算一下logo所在的坐标                      
                Graphics g = Graphics.FromImage(bCode);//创建一个画布                     
                g.DrawImage(bLogo, point);//将logo图片绘制到二维码图片上                    
                bCode.Save(qrpath);
            }
            catch
            {
                qrdir = "";
            }
            return qrdir;
        }
    }
}
